#!/usr/bin/env python
#coding:utf8
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import pymysql
from DBUtils.PooledDB import PooledDB
import datetime
import time

HOST="127.0.0.1"
USER="root"
PASSWORD= "123456"
DATABASE="english"

POOL = PooledDB(
    creator=pymysql, 
    maxconnections=10,
    mincached=2, 
    maxcached=5,
    maxshared=1, 
    blocking=True,
    maxusage=None, 
    setsession=[],
    ping=1,
    host=HOST,
    port=3306,
    user=USER,
    password=PASSWORD,
    database=DATABASE,
    charset='utf8'
)
def get_conn():
    conn = POOL.connection()
    cursor = conn.cursor()
    return conn, cursor

def put_conn(conn, cursor):
    conn.close()
    cursor.close()

def insert(**parameters):
    author = parameters['author']
    title = parameters['title'] 
    content = parameters['content']
    source = parameters['source'] 
    readers = parameters['readers'] 
    publish_time = parameters['publish_time']
    crawl_time = parameters['crawl_time']
    field = parameters['field']
    url = parameters['url']
    title = pymysql.escape_string(title)
    content = pymysql.escape_string(content)
    author = pymysql.escape_string(author)

    now = datetime.datetime.now()
    nowstr = now.strftime("%Y-%m-%d %H:%M:%S")
    conn, cursor = get_conn()
    sql = """insert into news(author, title, content, source, readers, publish_time, crawl_time, field, url)\
 values ("{0}","{1}","{2}","{3}",{4},"{5}","{6}", "{7}", "{8}")""".format(author, title, content, source, readers, publish_time, nowstr, field, url)
    #print sql
    cursor.execute(sql)
    conn.commit()
    put_conn(conn, cursor)

if __name__ == "__main__":
    print "run"
    insert("Jonn", "SHit", "I like it", "BBC", 33, "2020-01-02")
